package com.softright.net;

import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * 
 * @author lemon
 *
 */
public class StringBody extends MutilPartBody {
	
	private static final String CONTENT_TYPE = "Content-Type: text/plain";
	
	StringBody(String fieldName, String content) {
		StringBuffer sb = new StringBuffer();
		sb.append("Content-Disposition: form-data; name=\"" + fieldName + "\"");
		sb.append("\r\n");
		sb.append(CONTENT_TYPE);
		sb.append("\r\n");
		sb.append("\r\n");
		byte[] sb_bytes = sb.toString().getBytes();
		byte[] c_bytes = content.getBytes();
		length = sb_bytes.length + c_bytes.length;
		ByteBuffer byteBuffer = ByteBuffer.allocate(length);
		byteBuffer.put(sb_bytes);
		byteBuffer.put(c_bytes);
		bytes = byteBuffer.array();
	}

	@Override
	public void put(DataOutputStream os) throws FileUploadException {
		try {
			byte[] bytes = getBytes();
			os.write(bytes, 0, bytes.length);
		} catch (IOException e) {
			throw new FileUploadException(e);
		}
	}
}
